<template>
    <div class="upload-main-img" id="upload-main">
        <el-dialog title="上传图片" size="small" v-model="showPopover" @close="handleHidePopover" class="el-title">

            <div class="upload-img-list">
              <div class="upload-img-item" v-model="files" v-for="(item,index) in files">
                <div class="upload-operator" v-if='item.show == false && item.ashow'>
                  <span style="z-index: 120" class="iconfont icon-review" @click="handlePictureCardPreview(item)"></span>
                  <span style="z-index: 120" class="iconfont icon-del" @click="handleRemove(item.id,item.key)"></span>
                </div>
                <div class="upload-mask"  v-if='item.show == false && item.ashow'>      
                </div>
                <div class="item-id"></div>

                <div v-if="item.percent!=100 && item.show!=true" class="mdl-progress mdl-js-progress mdl-progress__indeterminate is-upgraded" data-upgraded=",MaterialProgress"
                >
                    <div class="progressbar bar bar1" :style="{width:item.percent}"></div>
                    <div class="bufferbar bar bar2" style="width: 100%;"></div>
                    <div class="auxbar bar bar3" style="width: 0%;"></div>
                </div>
                <div v-if='item.show == true'style="text-align: center;margin-top: 26px;">
                  <img style="width:12px;height:12px;display: inline-block;" src="../../assets/img/Combined Shape.png">
                  <span style="color: #F70000;font-size: 12px;margin-left: 2px;text-align: center">上传失败</span>
                </div>
                
               <img v-if="item.url!=null" v-lazy="item.url" :index='index'/>
              </div>

              <div id="upload-img-handler-container" v-show='files.length<8'>
                <div id="upload-img-handler">
                    <span class="iconfont icon-create-adv"></span>
                    <span class="up-txt">上传图片</span>
                </div>
                <!--div class="desc">*可拖拽或本地上传多张图片</div-->
              </div>
            </div>

            <div slot="footer">
                <div class="btn_common_white btn_common_small " @click="handleHidePopover">取消</div>
                <div :class="(files.length > 0 && files.length == upnumberSeccess) ? 'btn_common_yellow':'btn_common_grey_disable'" class="btn_common_small btn-common"  @click="submitUpload">上传</div>
            </div>
        </el-dialog>
        <div v-if='maskShow' class="mask-head" @click='maskShowChange'>
          <div>
            <i class="el-icon-close" style="cursor: pointer"></i>
            <img width="100%" :src="dialogImageUrl" alt="" @click.stop>
          </div>      
      </div>
    </div>
</template>
<script>
    import Vue from 'vue'
    import {SHOW_POPOVER_UPLOAD_IMG} from '~/store/mutation-types/upload'
    import { getCookie } from '~/assets/js/global';
    import { mapGetters } from 'Vuex'
    import { basicConfig } from '~/assets/js/config'
    import { Dialog,  Button, Message} from 'element-ui'
    Vue.use(Dialog);

    Vue.use(Button);

    export default{
        data(){
            return{
                files : [],
                dialogImageUrl: '',
                maskShow: false,
                loginToken: '',
                upnumberSeccess: 0,
            }
        },
        props:{
            dataType: {
                default : '0'
            },
            upload : {
              default : true
            },
        },
        methods: {

          handleHidePopover() {
             this.files = []
             this.uploader.files = []
             this.upnumberSeccess = 0
              this.$store.commit('SHOW_POPOVER_UPLOAD_IMG',{showPopoverUploadImg: false});
          },

          handleRemove(id,key) {
              this.$Lazyload.$off('loaded')
              this.$Lazyload.$off('error')
              this.$store.dispatch("deleteAddImgKey",{  
                  key:key
                  }).then(res=>{
                   
                })
              this.files.forEach((n,i)=>{
                if(n.id == id){
                  this.files.splice(i,1);
                  // this.uploader.files.splice(i,1)
                  this.upnumberSeccess --
                  // return;
                }
              });
          },
          handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            file.show = false
            this.maskShow = true
          },
          maskShowChange() {
            this.maskShow = false
          },

          submitUpload(){       
              if (this.files.length>0 && this.upnumberSeccess == this.files.length) {
                 if(this.dataType == '1'){
                     this.$parent.$parent['uploadImgSuccess'](this.files);
                 }else {
                     this.$parent['uploadImgSuccess'](this.files);
                 }
                this.$store.commit('SHOW_POPOVER_UPLOAD_IMG',{showPopoverUploadImg: false});
                this.files = []
                this.uploader.files = []
                this.upnumberSeccess = 0
              }       
              
          },

        　renderQiniuUpload(){                     
            //this.renderFlag = true;
            let _this = this;
            this.uploader = Qiniu.uploader({
              runtimes: 'html5',   
              browse_button: 'upload-img-handler',
              multi_selection : true,
              uptoken_url: basicConfig.baseUrl+'/assets/img/upToken.do?loginToken='+this.loginToken,
              //uptoken : '9svFtGE3GS1TCt5pG7wTNxWfYosWeKVEBCAGmMN_:7CKw5d_tHEUsJX4UgQgZObIS_lk=:eyJzY29wZSI6InRlc3QiLCJyZXR1cm5Cb2R5Ijoie1wibmFtZVwiOiQoZm5hbWUpLFwia2V5XCI6JChrZXkpfSIsImRlYWRsaW5lIjoxNDk0MzgzMzE5fQ==',
              filters : {
                  // max_file_size : '3mb',
                  prevent_duplicates: true,
                  mime_types: [
                      //{title : "Video files", extensions : "flv,mpg,mpeg,avi,wmv,mov,asf,rm,rmvb,mkv,m4v,mp4"},
                      {title : "Image files", extensions : "jpg,jpeg,gif,bmp,png"},
                  ]
              },
              domain: 'ads.onloon.net',  
              get_new_uptoken: false,
              container: 'upload-img-handler-container',
              max_file_size: '3mb',
              max_retries: 2,
              dragdrop: true,
              drop_element: 'upload-img-handler-container',
              //chunk_size: '100kb',
              auto_start: true,
              save_key:true,
              unique_names: true,
              init: {
                  'FilesAdded': function(up, files) {                     
                    plupload.each(files, function(file) {
                      if (_this.upload.toString() == 'true') {
                        if (_this.files.length > 7) {
                          // Message({
                          //   duration: 5000,
                          //   message: '最多上传八张图片',
                          //   type: 'error',
                          // })
                        }else {
                          _this.files.push(file)                       
                        }
                      }else {
                        if (_this.files.length > 4) {
                          // Message({
                          //   duration: 5000,
                          //   message: '最多上传八张图片',
                          //   type: 'error',
                          // })
                        }else {
                          _this.files.push(file)                        
                        }
                      }
                      
                    });
                    _this.uploader.files = []
                  },

                  'BeforeUpload': function(up, file) {
                    
                  },
                  'UploadProgress': function(up, file) {
                         // 每个文件上传时,处理相关的事情
                  },
                  'FileUploaded': function(up, file, info) {
                    _this.$Lazyload.$off('loaded')
                    _this.$Lazyload.$off('error')
                    Vue.nextTick(()=>{
                      _this.$Lazyload.$on('loaded', _this.handel)
                      _this.$Lazyload.$on('error', _this.handels)
                    })
                    let domain = up.getOption('domain');
                    let res = JSON.parse(info);
                    let url = domain + res.key;
                    _this.files.forEach((n,i)=>{
                      if(n.id == file.id){
                       _this.$store.dispatch("getUrlByKeyImg",{  
                          key:res.key
                          }).then(ress=>{
                            file.url = ress.data.data
                            file.key = res.key;
                            file.h = res.h;
                            file.w = res.w;
                            file.show = false
                            if (true) {}
                            if ((file.h >= 315 && file.w >= 600) || _this.upload == 'false') {
                              if (_this.upnumberSeccess>8) {
                                _this.upnumberSeccess = 8
                              }else {
                                _this.upnumberSeccess ++
                              }
                            
                              _this.files.splice(i,1,file);//updated
                              if(_this.$parent['uploadImageSuccess']){
                                  _this.$parent['uploadImageSuccess'](file);
                              }
                            }else {
                              _this.files.splice(i,1)
                              up.files.splice(i,1)
                              Message({
                                duration: 5000,
                                message: '请上传规定尺寸图片，至少600 * 315',
                                type: 'error',
                              })
                            }
                            
                            return;
                        })
                       
                      }
                    });

                  },
                  'Error': function(up, err, errTip) {
                    err.file.show = true
                    if (err.code == -600) {
                      Message({
                        duration: 5000,
                        message: '图片不能大于3M',
                        type: 'error',
                      })
                    }
                    
                    if (err.code == -602 ) {
                      Message.error('请不要重复上传');
                    }
                  },
                  'UploadComplete': function(up, file) {
                  },
                  'Key': function(up, file) {
                      var key = "";
                      return key
                  }
              }
            });


          },

          beforeUpload(file){
            
          },
          handel({el, naturalHeight, naturalWidth, $parent, src, loading, error, }, formCache) {
                var index = el.attributes['index'].value
                if (this.files) {
                  Vue.set(this.files[index],'ashow',true)
                }
                
          },
        },

        updated(){
           /*保证初始化一次*/
           !this.uploader && this.renderQiniuUpload();
        },
        computed:{
            ...mapGetters({
                    'showPopover': 'getShowPopoverUploadImg'
            })
        },
        created() {

        },
        mounted() {
          this.$Lazyload.$off('loaded');
          this.$Lazyload.$off('error');
          this.$Lazyload.$on('loaded', this.handel);
          this.$Lazyload.$on('error', this.handel);
          this.loginToken = getCookie('token');
        },
    }
</script>

<style lang="scss">
.upload-main-img{
      .mask-head {
          position: fixed;
          background-color: rgba(0, 0, 0, 0.84);
          width: 100%;
          height: 100%;
          right: 0;
          text-align: center;
          top: 0;
          z-index: 2020;
          div {
            width: 50%;
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%,-50%);
            i {
              position: absolute;
              top: 0;
              right: 0;
              color: #fff;
              transform: translate(-20%,-150%);
            }
            img {
              max-width: 100%;
            }
          }
        }
    .el-input {
        width: 172px;
        height: 28px;
    }
    .btn-common {
        margin-left: 10px;
    }
    .btn_common_small{
        line-height: 17px;
    }
    .btn_common_white:hover {
      background-color: #EAEEF0;
    }
    .el-dialog--small{
        width: 801px;
    }
    #upload-img-handler-container {
      position:relative;
      border-radius: 4px;
      height: 90px;
      display: inline-block;
      background-color: #f3f7fa;
      border:1px #d7dee4 dashed;
      cursor: pointer;
      .desc{
        position:absolute;
        bottom:-25px;
        left: -45px;
        display: block;
        width: 200px;
      }
      &:hover {
        border-color: #20a0ff;
      }

    }
    .upload-mask {
       width: 78px;
      height: 78px;
      position:absolute;
      display: none;
      vertical-align: middle;
      padding-top:28px;
      height: 50px;
      z-index: 99;
      background-color:#000;
      opacity: .3;
    }

    .upload-operator{
      display: none;
      vertical-align: middle;
      padding-top:28px;
      height: 50px;
      z-index: 100;
      width: 78px;
      height: 78px;
      position:absolute;
      span{
        color:#fff;
        font-size:16px;
        margin-left: 13px;
        display: inline-block;
        vertical-align: middle;
        cursor: pointer;
      }
      &:hover {
        display: block;
      }
    }

    .upload-img-item:hover .upload-operator{
      display: block;
    }
    .upload-img-item:hover .upload-mask{
      display: block;
    }
    #upload-img-handler{
      padding-top:20px;
      width: 90px;
      height: 70px;
      text-align: center;
    }

    .up-txt{
      display: block;
      text-align: center;
    }

    .el-dialog--small .el-dialog__body{
      height: 300px;
      overflow-y: auto;
    }

    .upload-img-list{
      display: flex;
      flex-wrap:wrap;
    }
    .upload-img-item{
      position:relative;
      width: 78px;
      height:78px;
      padding:6px;
      border:1px #D5DFE4 solid;
      border-radius: 4px;
      margin: 0 14px 14px 0;
      img[lazy=loaded]{
        display: block;
        width: 78px;
        height: 78px;
        border-radius: 4px;
      }
      img[lazy=loading] {
          height: 18px!important;
          width: 18px!important;
          position: absolute;
          left: 50%;
          top: 50%;
          transform:translate(-50%,-50%);
        }
        img[lazy=error] {
          height: 18px!important;
          width:24px!important;
          position: absolute;
          left: 50%;
          top: 50%;
          transform:translate(-50%,-50%);
        }
    }

    .item-id{
      position:absolute;
    }
    .mdl-progress {
        display: block;
        position: absolute;
        top:40px;
        height: 6px;
        width: 76px;
        max-width: 100%
    }

    .mdl-progress>.bar {
        display: block;
        position: absolute;
        top: 0;
        bottom: 0;
        width: 0%;
        transition: width .2s cubic-bezier(.4,0,.2,1)
    }

    .mdl-progress>.progressbar {
        background-color: #fffaea;
        z-index: 1;
        left: 0
    }

    .mdl-progress>.bufferbar {
        /*background-image: linear-gradient(to right,rgba(255,255,255,.7),rgba(255,255,255,.7)),linear-gradient(to right,#3f51b5 ,#3f51b5);*/
        border: 1px #ffb100 solid;
        border-radius:8px;
        background-color:#fffaea;
        z-index: 0;
        left: 0
    }

    .mdl-progress>.auxbar {
        right: 0;
        height: 6px;
    }

    @supports (-webkit-appearance: none) {
        .mdl-progress:not(.mdl-progress--indeterminate):not(.mdl-progress--indeterminate)>.auxbar,.mdl-progress:not(.mdl-progress__indeterminate):not(.mdl-progress__indeterminate)>.auxbar {
            /*background-image:linear-gradient(to right,rgba(255,255,255,.7),rgba(255,255,255,.7)),linear-gradient(to right,#3f51b5 ,#3f51b5);*/
            padding-top:1px;
            height: 5px;
            border-radius:none;
            -webkit-mask: url("");
            mask: url("")
        }
    }

    .mdl-progress:not(.mdl-progress--indeterminate)>.auxbar,.mdl-progress:not(.mdl-progress__indeterminate)>.auxbar {
        /*background-image: linear-gradient(to right,rgba(255,255,255,.9),rgba(255,255,255,.9)),linear-gradient(to right,#3f51b5 ,#3f51b5)*/
        background-color: transparent;
    }

    .mdl-progress.mdl-progress--indeterminate>.bar1,.mdl-progress.mdl-progress__indeterminate>.bar1 {
        -webkit-animation-name: indeterminate1;
        animation-name: indeterminate1
    }

    .mdl-progress.mdl-progress--indeterminate>.bar1,.mdl-progress.mdl-progress__indeterminate>.bar1,.mdl-progress.mdl-progress--indeterminate>.bar3,.mdl-progress.mdl-progress__indeterminate>.bar3 {

        -webkit-animation-duration: 2s;
        animation-duration: 2s;
        -webkit-animation-iteration-count: infinite;
        animation-iteration-count: infinite;
        -webkit-animation-timing-function: linear;
        animation-timing-function: linear
    }

    .mdl-progress__indeterminate .bar1{
      border-radius:8px;
      background-color: #e80;
    }

    .mdl-progress.mdl-progress--indeterminate>.bar3,.mdl-progress.mdl-progress__indeterminate>.bar3 {
        
        background-image: none;
        -webkit-animation-name: indeterminate2;
        animation-name: indeterminate2
    }

    @-webkit-keyframes indeterminate1 {
        0% {
            left: 0%;
            width: 0%
        }

        50% {
            left: 25%;
            width: 75%
        }

        75% {
            left: 100%;
            width: 0%
        }
    }

    @keyframes indeterminate1 {
        0% {
            left: 0%;
            width: 0%
        }

        50% {
            left: 25%;
            width: 75%
        }

        75% {
            left: 100%;
            width: 0%
        }
    }

    @-webkit-keyframes indeterminate2 {
        0%,50% {
            left: 0%;
            width: 0%
        }

        75% {
            left: 0%;
            width: 25%
        }

        100% {
            left: 100%;
            width: 0%
        }
    }

    @keyframes indeterminate2 {
        0%,50% {
            left: 0%;
            width: 0%
        }

        75% {
            left: 0%;
            width: 25%
        }

        100% {
            left: 100%;
            width: 0%
        }
    }

}
</style>
